package com.example.demo.rx;

import com.example.demo.rx.cat.ApiWrapper3Job;
import com.example.demo.rx.cat.AsyncJob;
import com.example.demo.rx.cat.Callback;
import com.example.demo.rx.cat.Cat;

import java.net.URL;
import java.util.Collections;
import java.util.List;

public class CatsHelper3Job0 {
    ApiWrapper3Job apiWrapper;
    public AsyncJob<URL> saveTheCutest(String query) {
        return new AsyncJob<URL>() {
            @Override
            public void start(Callback<URL> callback) {
                apiWrapper.queryCats(query)
                        .start(new Callback<List<Cat>>() {
                            @Override
                            public void onResult(List<Cat> cats) {
                                Cat cutest = findCutest(cats);
                                apiWrapper.store(cutest).start(new Callback<URL>() {
                                    @Override
                                    public void onResult(URL result) {
                                        callback.onResult(result);
                                    }

                                    @Override
                                    public void onError(Exception e) {
                                        callback.onError(e);
                                    }
                                });
                            }

                            @Override
                            public void onError(Exception e) {
                                callback.onError(e);
                            }
                        });
            }
        };
    }

    private Cat findCutest(List<Cat> cats) {
        return Collections.max(cats);
    }
}
